<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4">
        <div class="tree-container">
          <el-tree
            :data="typeOptions"
            :props="treeProps"
            :highlight-current="true"
            @node-click="handleTreeClick"
            node-key="itemTypeId"
            default-expand-all
            :expand-on-click-node="false"
          >
            <span slot-scope="{ node }">
              <span>{{ node.label }}</span>
            </span>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="20">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="物料编码" prop="itemCode">
            <el-input
              v-model="queryParams.itemCode"
              placeholder="请输入物料编码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="物料名称" prop="itemName">
            <el-input
              v-model="queryParams.itemName"
              placeholder="请输入物料名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="是否启用" prop="enableFlag">
            <el-select
              v-model="queryParams.enableFlag"
              placeholder="请选择是否启用"
              clearable
            >
              <el-option
                v-for="dict in dict.type.enable_flag"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:item:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:item:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:item:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:item:export']"
              >导出</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="itemList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="物料编码" align="center" prop="itemCode">
            <template slot-scope="scope">
              <el-button type="text" @click="handleView(scope.row)">{{
                scope.row.itemCode
              }}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" align="center" prop="itemName" />
          <el-table-column
            label="规格型号"
            align="center"
            prop="specification"
          />
          <el-table-column label="单位" align="center" prop="unitOfMeasure" />
          <el-table-column
            label="物料/产品"
            align="center"
            prop="itemOrProduct"
          >
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.item_or_product"
                :value="scope.row.itemOrProduct"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="物料类型名称"
            align="center"
            prop="itemTypeName"
          />
          <el-table-column label="是否启用" align="center" prop="enableFlag">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.enable_flag"
                :value="scope.row.enableFlag"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="是否设置安全库存"
            align="center"
            prop="safeStockFlag"
          />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            width="180"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:item:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:item:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改物料产品对话框 -->
        <el-dialog
          :title="title"
          :visible.sync="open"
          width="900px"
          append-to-body
        >
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row :gutter="20">
              <!-- 左侧表单列 -->
              <el-col :span="16">
                <el-row :gutter="15">
                  <el-col :span="24">
                    <el-form-item label="物料名称" prop="itemName">
                      <el-input
                        v-model="form.itemName"
                        placeholder="请输入物料名称"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-form-item label="规格型号" prop="specification">
                      <el-input
                        v-model="form.specification"
                        placeholder="请输入规格型号"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="单位" prop="unitOfMeasure">
                      <el-select
                        v-model="form.unitOfMeasure"
                        placeholder="请选择单位"
                        clearable
                      >
                        <el-option
                          v-for="item in itemOptions"
                          :key="item.measureId"
                          :label="item.measureName"
                          :value="item.measureCode"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="物料分类" prop="itemTypeName">
                      <treeselect
                        v-model="form.itemTypeId"
                        :options="typeOptions"
                        :normalizer="normalizer"
                        @select="handleTypeSelect"
                        placeholder="请选择物料分类"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-form-item
                      label="高价值物品"
                      prop="highValue"
                      label-width="120px"
                    >
                      <el-checkbox
                        v-model="form.highValue"
                        :true-label="'Y'"
                        :false-label="'N'"
                        >是（高价值/易被盗物品）</el-checkbox
                      >
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="是否启用" prop="enableFlag">
                      <el-radio-group v-model="form.enableFlag">
                        <el-radio label="Y">启用</el-radio>
                        <el-radio label="N">停用</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="批次管理" prop="batchFlag">
                      <el-switch
                        v-model="form.batchFlag"
                        active-text="启用"
                        inactive-text="停用"
                        active-value="Y"
                        inactive-value="N"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-form-item label="安全库存" prop="safeStockFlag">
                      <el-radio-group v-model="form.safeStockFlag">
                        <el-radio label="Y">需要安全库存</el-radio>
                        <el-radio label="N">无需安全库存</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-row
                    v-if="form.safeStockFlag === 'Y'"
                    :gutter="15"
                    class="safe-stock-container"
                  >
                    <el-col :span="12">
                      <el-form-item
                        label="最小库存量"
                        prop="minStock"
                        :rules="
                          form.safeStockFlag === 'Y'
                            ? [{ required: true, message: '不能为空' }]
                            : []
                        "
                      >
                        <el-input-number
                          v-model="form.minStock"
                          :precision="2"
                          :step="1"
                          controls-position="right"
                          style="width: 100%"
                          placeholder="最小库存"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label="最大库存量"
                        prop="maxStock"
                        :rules="
                          form.safeStockFlag === 'Y'
                            ? [{ required: true, message: '不能为空' }]
                            : []
                        "
                      >
                        <el-input-number
                          v-model="form.maxStock"
                          :precision="2"
                          :step="1"
                          controls-position="right"
                          style="width: 100%"
                          placeholder="最大库存"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-col :span="24">
                    <el-form-item label="备注" prop="remark">
                      <el-input
                        v-model="form.remark"
                        type="textarea"
                        :rows="2"
                        placeholder="请输入备注信息"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

              <!-- 右侧二维码列 -->
              <el-col :span="8">
                <div class="qrcode-card">
                  <div v-if="!qrcodeUrl" class="qrcode-loading">生成中...</div>
                  <img v-else :src="qrcodeUrl" class="qrcode-image" />
                </div>
              </el-col>
            </el-row>
            <el-divider content-position="center">产品BOM关系信息</el-divider>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAddMdProductBom"
                  >添加</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="handleDeleteMdProductBom"
                  >删除</el-button
                >
              </el-col>
            </el-row>
            <el-table
              :data="mdProductBomList"
              :row-class-name="rowMdProductBomIndex"
              @selection-change="handleMdProductBomSelectionChange"
            >
              <el-table-column type="selection" align="center" />
              <el-table-column label="BOM物料ID" prop="bomItemId" width="200">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.bomItemId"
                    placeholder="请输入物料ID"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="BOM物料编码"
                prop="bomItemCode"
                width="200"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.bomItemCode"
                    placeholder="请输入物料编码"
                  />
                </template>
              </el-table-column>

              <el-table-column
                label="BOM物料名称"
                prop="bomItemName"
                width="200"
              >
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.bomItemName"
                    filterable
                    clearable
                    placeholder="请选择BOM物料名称"
                    @change="handleMaterialChange(scope.row.bomItemName, scope)"
                  >
                    <el-option
                      v-for="item in materialList"
                      :key="item.itemName"
                      :label="item.itemName"
                      :value="item.itemName"
                    />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column label="规格" prop="bomItemSpec" width="200">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.bomItemSpec"
                    placeholder="请输入规格"
                  />
                </template>
              </el-table-column>

              <el-table-column label="单位" prop="unitOfMeasure" width="200">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.unitOfMeasure"
                    placeholder="请输入单位"
                  />
                </template>
              </el-table-column>
              <el-table-column label="使用比例" prop="quantity" width="200">
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.quantity"
                    controls-position="right"
                    :min="0"
                    :step="0.1"
                    :precision="1"
                  />
                </template>
              </el-table-column>
              <el-table-column label="标识" prop="itemOrProduct" width="200">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.itemOrProduct" />
                </template>
              </el-table-column>
              <el-table-column label="是否启用" prop="enableFlag" width="200">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.enableFlag"
                    active-text="启用"
                    inactive-text="停用"
                    active-value="Y"
                    inactive-value="N"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
        <!-- 查看物料产品 -->
        <el-dialog
          title="查看物料产品"
          :visible.sync="show"
          width="900px"
          append-to-body
        >
          <el-form ref="form" :model="form" label-width="120px">
            <el-row :gutter="20">
              <!-- 左侧表单列 -->
              <el-col :span="16">
                <el-row :gutter="15">
                  <el-col :span="24">
                    <el-form-item label="物料名称" prop="itemName">
                      <el-input
                        v-model="form.itemName"
                        placeholder="请输入物料名称"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-form-item label="规格型号" prop="specification">
                      <el-input
                        v-model="form.specification"
                        placeholder="请输入规格型号"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="单位" prop="unitOfMeasure">
                      <el-select
                        v-model="form.unitOfMeasure"
                        placeholder="请选择单位"
                        clearable
                      >
                        <el-option
                          v-for="item in itemOptions"
                          :key="item.measureId"
                          :label="item.measureName"
                          :value="item.measureCode"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="物料分类" prop="itemTypeName">
                      <treeselect
                        v-model="form.itemTypeId"
                        :options="typeOptions"
                        :normalizer="normalizer"
                        @select="handleTypeSelect"
                        placeholder="请选择物料分类"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-form-item
                      label="高价值物品"
                      prop="highValue"
                      label-width="120px"
                    >
                      <el-checkbox
                        v-model="form.highValue"
                        :true-label="'Y'"
                        :false-label="'N'"
                        >是（高价值/易被盗物品）</el-checkbox
                      >
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="是否启用" prop="enableFlag">
                      <el-radio-group v-model="form.enableFlag">
                        <el-radio label="Y">启用</el-radio>
                        <el-radio label="N">停用</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="批次管理" prop="batchFlag">
                      <el-switch
                        v-model="form.batchFlag"
                        active-text="启用"
                        inactive-text="停用"
                        active-value="Y"
                        inactive-value="N"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-form-item label="安全库存" prop="safeStockFlag">
                      <el-radio-group v-model="form.safeStockFlag">
                        <el-radio label="Y">需要安全库存</el-radio>
                        <el-radio label="N">无需安全库存</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-row
                    v-if="form.safeStockFlag === 'Y'"
                    :gutter="15"
                    class="safe-stock-container"
                  >
                    <el-col :span="12">
                      <el-form-item
                        label="最小库存量"
                        prop="minStock"
                        :rules="
                          form.safeStockFlag === 'Y'
                            ? [{ required: true, message: '不能为空' }]
                            : []
                        "
                      >
                        <el-input-number
                          v-model="form.minStock"
                          :precision="2"
                          :step="1"
                          controls-position="right"
                          style="width: 100%"
                          placeholder="最小库存"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label="最大库存量"
                        prop="maxStock"
                        :rules="
                          form.safeStockFlag === 'Y'
                            ? [{ required: true, message: '不能为空' }]
                            : []
                        "
                      >
                        <el-input-number
                          v-model="form.maxStock"
                          :precision="2"
                          :step="1"
                          controls-position="right"
                          style="width: 100%"
                          placeholder="最大库存"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-col :span="24">
                    <el-form-item label="备注" prop="remark">
                      <el-input
                        v-model="form.remark"
                        type="textarea"
                        :rows="2"
                        placeholder="请输入备注信息"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

              <!-- 右侧二维码列 -->
              <el-col :span="8">
                <div class="qrcode-card">
                  <div v-if="!qrcodeUrl" class="qrcode-loading">生成中...</div>
                  <img v-else :src="qrcodeUrl" class="qrcode-image" />
                </div>
              </el-col>
            </el-row>
            <el-divider content-position="center">产品BOM关系信息</el-divider>
            <el-table
              :data="mdProductBomList"
              :row-class-name="rowMdProductBomIndex"
              @selection-change="handleMdProductBomSelectionChange"
            >
              <!-- 在查看对话框中修改BOM表格列 -->
              <el-table-column label="BOM物料ID" prop="bomItemId" width="200">
                <template slot-scope="scope">
                  <span>{{ scope.row.bomItemId }}</span>
                  <!-- 替换input为文本 -->
                </template>
              </el-table-column>

              <el-table-column
                label="BOM物料编码"
                prop="bomItemCode"
                width="200"
              >
                <template slot-scope="scope">
                  <span>{{ scope.row.bomItemCode }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="BOM物料名称"
                prop="bomItemName"
                width="200"
              >
                <template slot-scope="scope">
                  <span>{{ scope.row.bomItemName }}</span>
                  <!-- 替换select为文本 -->
                </template>
              </el-table-column>

              <el-table-column label="规格" prop="bomItemSpec" width="200">
                <template slot-scope="scope">
                  <span>{{ scope.row.bomItemSpec }}</span>
                </template>
              </el-table-column>

              <el-table-column label="单位" prop="unitOfMeasure" width="200">
                <template slot-scope="scope">
                  <span>{{ scope.row.unitOfMeasure }}</span>
                </template>
              </el-table-column>

              <el-table-column label="使用比例" prop="quantity" width="200">
                <template slot-scope="scope">
                  <span>{{ scope.row.quantity }}</span>
                </template>
              </el-table-column>

              <el-table-column label="标识" prop="itemOrProduct" width="200">
                <template slot-scope="scope">
                  <dict-tag
                    :options="dict.type.item_or_product"
                    :value="scope.row.itemOrProduct"
                  />
                </template>
              </el-table-column>

              <el-table-column label="是否启用" prop="enableFlag" width="200">
                <template slot-scope="scope">
                  <dict-tag
                    :options="dict.type.enable_flag"
                    :value="scope.row.enableFlag"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  listItem,
  getItem,
  delItem,
  addItem,
  updateItem,
} from "@/api/system/item";

import { listMeasure } from "@/api/system/measure";

import QRCode from "qrcode";
import { listType } from "@/api/system/type";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  components: {
    Treeselect,
  },
  name: "Item",
  dicts: ["item_or_product", "enable_flag"],
  data() {
    return {
      // 新增树形配置
      treeProps: {
        children: "children",
        label: "itemTypeName",
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料产品表格数据
      itemList: [],
      materialList: [], // 新增物料产品列表
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      show: false,
      itemOptions: [],
      // 新增分类树数据
      typeOptions: [],
      // 产品BOM关系表格数据
      mdProductBomList: [],
      qrcodeUrl: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemCode: null,
        itemName: null,
        enableFlag: null,
        itemTypeId: null, // 新增分类ID参数
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        itemCode: [
          { required: true, message: "物料编码不能为空", trigger: "blur" },
        ],
        itemName: [
          { required: true, message: "物料名称不能为空", trigger: "blur" },
        ],
        unitOfMeasure: [
          { required: true, message: "单位不能为空", trigger: "blur" },
        ],
        enableFlag: [
          { required: true, message: "是否启用不能为空", trigger: "change" },
        ],
        safeStockFlag: [
          {
            required: true,
            message: "是否设置安全库存不能为空",
            trigger: "blur",
          },
        ],
        highValue: [
          { required: true, message: "高价值物资不能为空", trigger: "blur" },
        ],
        batchFlag: [
          { required: true, message: "是否批次管理不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getMaterialList();
  },
  methods: {
    /** 查询物料产品列表 */
    getList() {
      this.loading = true;
      listItem(this.queryParams).then((response) => {
        this.itemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listMeasure().then((response) => {
        this.itemOptions = response.rows;
      });
      listType(this.queryParams).then((response) => {
        this.typeOptions = this.handleTree(
          response.data,
          "itemTypeId",
          "parentTypeId"
        );
      });
      console.log(this.typeOptions);
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.itemTypeId,
        label: node.itemTypeName,
        children: node.children,
        // 追加需要传递的数据
        itemTypeCode: node.itemTypeCode,
        itemTypeName: node.itemTypeName,
        itemOrProduct: node.itemOrProduct,
      };
    },
    // 分类选择事件
    handleTypeSelect(node) {
      this.form.itemTypeId = node.itemTypeId;
      this.form.itemTypeCode = node.itemTypeCode; // 假设接口返回了编码字段
      this.form.itemTypeName = node.itemTypeName;
      this.form.itemOrProduct = node.itemOrProduct;
    },
    // 新增树节点点击处理
    handleTreeClick(data) {
      this.queryParams.itemTypeId = data.itemTypeId;
      this.handleQuery();
    },
    /** 新增：获取物料列表 */
    getMaterialList() {
      listItem({ pageSize: 1000 }).then((response) => {
        this.materialList = response.rows;
      });
    },
    // 新增：物料选择变化处理
    handleMaterialChange(val, scope) {
      const selected = this.materialList.find((item) => item.itemName === val);
      if (selected) {
        scope.row.bomItemId = selected.itemId;
        scope.row.bomItemCode = selected.itemCode;
        scope.row.bomItemSpec = selected.specification;
        scope.row.unitOfMeasure = selected.unitOfMeasure;
        scope.row.itemOrProduct = selected.itemOrProduct;
        scope.row.enableFlag = selected.enableFlag;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.show = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        itemOrProduct: null,
        itemTypeId: null,
        itemTypeCode: null,
        itemTypeName: null,
        enableFlag: null,
        safeStockFlag: null,
        minStock: null,
        maxStock: null,
        highValue: null,
        batchFlag: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.mdProductBomList = [];
      this.resetForm("form");
    },
    // 查询明细按钮操作
    async handleView(row) {
      this.reset();
      this.form = {
        itemId: row.itemId,
        itemCode: row.itemCode,
        itemName: row.itemName,
        specification: row.specification,
        unitOfMeasure: row.unitOfMeasure,
        itemOrProduct: row.itemOrProduct,
        itemTypeId: row.itemTypeId,
        itemTypeCode: row.itemTypeCode,
        itemTypeName: row.itemTypeName,
        enableFlag: row.enableFlag,
        safeStockFlag: row.safeStockFlag,
        minStock: row.minStock,
        maxStock: row.maxStock,
        highValue: row.highValue,
        batchFlag: row.batchFlag,
        remark: row.remark,
      };
      const itemId = row.itemId;
      getItem(itemId).then((response) => {
        this.form = response.data;
        this.mdProductBomList = response.data.mdProductBomList; // 加载BOM数据
        this.generateQRCode(this.form.itemCode);
        this.show = true;
      });
    },
    // 新增二维码生成方法
    async generateQRCode(content) {
      this.qrcodeUrl = await QRCode.toDataURL(content, {
        width: 200,
        margin: 2,
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.itemTypeId = null; // 重置分类ID
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.itemId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物料产品";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const itemId = row.itemId || this.ids;
      getItem(itemId).then(async (response) => {
        this.form = response.data;
        this.mdProductBomList = response.data.mdProductBomList;
        await this.generateQRCode(this.form.itemCode);
        this.open = true;
        this.title = "修改物料产品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.mdProductBomList = this.mdProductBomList;
          if (this.form.itemId != null) {
            updateItem(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addItem(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const itemIds = row.itemId || this.ids;
      this.$modal
        .confirm('是否确认删除物料产品编号为"' + itemIds + '"的数据项？')
        .then(function () {
          return delItem(itemIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/item/export",
        {
          ...this.queryParams,
        },
        `item_${new Date().getTime()}.xlsx`
      );
    },
    /** 产品BOM关系序号 */
    rowMdProductBomIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 产品BOM关系添加按钮操作 */
    handleAddMdProductBom() {
      let obj = {};
      obj.bomItemCode = "";
      obj.bomItemName = "";
      obj.bomItemSpec = "";
      obj.unitOfMeasure = "";
      obj.quantity = "";
      obj.remark = "";
      this.mdProductBomList.push(obj);
    },
    /** 产品BOM关系删除按钮操作 */
    handleDeleteMdProductBom() {
      if (this.checkedMdProductBom.length == 0) {
        this.$modal.msgError("请先选择要删除的产品BOM关系数据");
      } else {
        const mdProductBomList = this.mdProductBomList;
        const checkedMdProductBom = this.checkedMdProductBom;
        this.mdProductBomList = mdProductBomList.filter(function (item) {
          return checkedMdProductBom.indexOf(item.index) == -1;
        });
      }
    },
    /** 复选框选中数据 */
    handleMdProductBomSelectionChange(selection) {
      this.checkedMdProductBom = selection.map((item) => item.index);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/item/export",
        {
          ...this.queryParams,
        },
        `item_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>